package config

import (
	"errors"
	"log"
	"os"
	"sync"

	"gopkg.in/yaml.v3"
)

// ------------------------------------------------------------------------------
// singleton
// ------------------------------------------------------------------------------
type Configer struct {
	Data ConfigData
}

var instance *Configer
var once sync.Once

func Instance() *Configer {
	once.Do(func() {
		instance = &Configer{}
	})
	return instance
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func (configer *Configer) Init(configFile string) error {
	data, err := os.ReadFile(configFile)
	if err != nil {
		log.Fatalf("read config file:%s failed", configFile)
		return errors.New("read config file failed")
	}

	err = yaml.Unmarshal(data, &configer.Data)
	if err != nil {
		log.Fatal("unmarshal config failed")
		return errors.New("unmarshal config failed")
	}

	return nil
}
